﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading; 
using System.IO;
using MediaMonitor.Common;

namespace MediaMonitor.sitefiles
{
    public partial class display_pdf : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["Page"] != null)
            {
                 PDFGenerator pGen = new  PDFGenerator(Server.MapPath("~/pdf"));
                 string sFile = pGen.RunWeb(Server.UrlDecode(Request["Url"].ToString()));

                Response.Redirect("display-pdf.aspx?File=" + sFile);
            }

            if (Request.Params["File"] != null)
            {
                bool bRet = false;
                int iTimeout = 0;
                while (bRet == false)
                {
                    bRet = CheckIfFileExist(Request.Params["File"].ToString());
                    Thread.Sleep(1000);
                    iTimeout++;
                    if (iTimeout == 10)
                        break;
                }

                if (bRet == true)
                {
                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.ContentType = "Application/pdf";
                    try
                    {
                        Response.WriteFile(MapPath("" + Request.Params["File"].ToString()));
                        Response.Flush();
                        Response.Close();
                    }
                    catch
                    {
                        Response.ClearContent();
                    }

                }
                else
                {
                    if (Request.Params["Msg"] != null)
                    {
                        LabelMsg.Text = Request.Params["Msg"].ToString();
                    }
                }
            }
        }

        private bool CheckIfFileExist(string sFile)
        {
            string sRoot = Server.MapPath("~/pdf");
            string sDrive = "" + sRoot[0];

            if (File.Exists(MapPath("" + Request.Params["File"].ToString())) == false)
            {

                return (false);
            }

            return (true);
        }


        protected void BT_PDFReady_Click(object sender, System.EventArgs e)
        {
            string sMsg = "Please wait a few seconds and press the button again";

            if (Request.Params["Msg"] != null)
                sMsg = "This report takes longer than normal, wait 10 seconds and press the button again";

            if (Request.Params["File"] != null)
            {
                Response.Redirect("display-pdf.aspx?File=" + Request.Params["File"].ToString() + "&Msg=" + sMsg);
            }
        }
    }
}